﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;
using System.Collections;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
namespace VSM
{
    public partial class P_Reservation : System.Web.UI.Page
    {

 
        private static GeneralFunctions GF = null;

        //private static int ServiceID = -1;
        //private static int ResID = -1;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                          || Session[Utils.AppConstants.Password] == null
                          || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            
            if (!IsPostBack)
            {
                //dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                Session["GeneralID"] = Request.QueryString["GeneralID"] == null ? "-1" : Request.QueryString["GeneralID"];
                Session["ResID"] = Request.QueryString["ResID"] == null ? "-1" : Request.QueryString["ResID"];

                if (Session["ResID"].ToString() == "-1" && Session["GeneralID"].ToString() == "-1")
                {
                    createEmptyTable();
                    generateNewAppID();
                    loadDefaultData();
                }
                else if (Session["ResID"].ToString() != "-1") {
                    loadDataByResID();
                }
                else
                    if (Session["GeneralID"].ToString() != "-1")
                {
                    loadDefaultData();
                    generateNewAppID();
                    loadDataByServiceID();
                    createEmptyTable();
                }
                
                // Add code check security here
                
                if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 0)
                {
                    //txtDealerCode.ReadOnly = true;
                    //txtDealerCode.BackColor = ColorTranslator.FromHtml("#E6E6E6");
                    //hf_GeneralID.Value = Request.QueryString["id"];
                    //btnUpdate.Text = "Update Dealer";
                    if (string.Compare("VSM", (string)Session[Utils.AppConstants.ID_Dealer]) == 0)
                    {
                        
                    }
                }
                else if (string.Compare("VSM", (string)Session[Utils.AppConstants.ID_Dealer]) == 0) // Add new dealer
                {
                    //btnUpdate.Text = "Add Dealer";
                    //DealerCode.Value = "";
                }
            }
        }

        

        private void createEmptyTable()
        {
            DataTable dtTmp = new DataTable();
            dtTmp.Columns.Add("No");
            dtTmp.Columns.Add("DetailCode");
            dtTmp.Columns.Add("ItemCode");
            dtTmp.Columns.Add("ItemName");
            dtTmp.Columns.Add("FrgnName");
            dtTmp.Columns.Add("Quantity");
            dtTmp.Columns.Add("Price");
            dtTmp.Columns.Add("VAT");
            dtTmp.Columns.Add("DiscPrcnt");
            dtTmp.Columns.Add("Stock");

            Session["dtDetail"] = dtTmp;
            grvPO.DataSource = dtTmp;
            grvPO.DataBind();

        }
        private void generateNewAppID()
        {
            DateTime curr = DateTime.Now;
            
            Services sv = new Services();
            string sql = "select RIGHT('000' + CAST(count(*) + 1 as nvarchar(5)), 3) as GreatestNum from U_Reservation where MONTH(ResDate) = " + curr.Month.ToString() + " and YEAR(ResDate) = " + curr.Year.ToString() + " and DealerCode = '" + Session[Utils.AppConstants.ID_Dealer].ToString() + "'";
            DataSet dsJobID = sv.ExecuteQuery("DEALER", sql);
            if (dsJobID.Tables[0].Rows.Count > 0) {
                
                txt_SeqNo.Text = "AP-" + dsJobID.Tables[0].Rows[0]["GreatestNum"].ToString() + "/" + curr.ToString("MMyy");
            }
            
        }

        private void loadDefaultData() {
            txt_Odometer.Text = "0";
            DateTime currDate = DateTime.Now;
            txt_ResDate.Text = currDate.ToString("dd/MM/yyyy");
            Services svc = new Services();
            DataSet ds =  svc.ExecuteQuery("VSM", "select UserName from tbl_MasterUsers where ID_User = '" + Session[Utils.AppConstants.ID_User] + "'" );
            if (ds.Tables[0].Rows.Count > 0) {
                txt_Receptionist.Text = ds.Tables[0].Rows[0]["UserName"].ToString();
            }


        }

        
        private string FormatDate(string dateIn) {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");
        }

        private void loadDataByResID()
        {
            string sql = "SELECT [ResID],[SeqNo],[ServiceStaff],[ResDate],[ResTime],[DeliveryDate] ";
            sql += " ,[DeliveryTime],[ConfirmDate],[ConfirmTime],[CustomerCall],[EstimateCost] ";
            sql += " ,[PODate],[POTime],[PADate],[PATime],[CustomerRequest] ";
            sql += " ,[VehicleID],[VIN],[Brand],[VehicleName],[EngineNo] ";
            sql += " ,[RegNo],[Model],[ColorCode],[Odometer],[CustomerID] ";
            sql += " ,[CustomerName],[OtherName],[Address],[Tel],[Mobile] ";
            sql += " ,[TaxCode],[ContactPerson],[ContactPhone],[DealerCode] ";
            sql += "  FROM [Dealer_Test].[dbo].[U_Reservation] ";
            sql += "  WHERE ResID = " + Session["ResID"].ToString();
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            if (ds.Tables[0].Rows.Count > 0)
            {

                DataRow dr = ds.Tables[0].Rows[0];
                hf_ResID.Value = Session["ResID"].ToString();
                txt_SeqNo.Text = dr["SeqNo"].ToString();
                txt_Receptionist.Text = dr["ServiceStaff"].ToString();
                txt_ResDate.Text = FormatDate(dr["ResDate"].ToString());
                txt_ResTime.Text = dr["ResTime"].ToString();
                txt_DelDate.Text = FormatDate(dr["DeliveryDate"].ToString());

                txt_DelTime.Text = dr["DeliveryTime"].ToString();
                txt_ConfDate.Text = FormatDate(dr["ConfirmDate"].ToString());
                txt_ConfTime.Text = dr["ConfirmTime"].ToString();
                chk_CustomerCall.Checked = Boolean.Parse( dr["CustomerCall"].ToString());
                txt_EstimateCost.Text = dr["EstimateCost"].ToString();

                txt_PartOrderDate.Text = FormatDate(dr["PODate"].ToString());
                txt_PartOrderTime.Text = dr["POTime"].ToString();
                txt_PartArrivalDate.Text = FormatDate(dr["PADate"].ToString());
                txt_PartArrivalTime.Text = dr["PATime"].ToString();
                txt_CustomerRequest.Text = dr["CustomerRequest"].ToString();

                hf_CustomerCode.Value = dr["CustomerID"].ToString();
                hf_VehicleID.Value = dr["VehicleID"].ToString();

                txt_CustomerName.Text = dr["CustomerName"].ToString();
                txt_OtherName.Text = dr["OtherName"].ToString();
                txt_Address.Text = dr["Address"].ToString();
                txt_Tel.Text = dr["Tel"].ToString();
                txt_Mobile.Text = dr["Mobile"].ToString();
                txt_TaxCode.Text = dr["TaxCode"].ToString();
                txt_ContactPerson.Text = dr["ContactPerson"].ToString();
                txt_PhoneContact.Text = dr["ContactPhone"].ToString();

                txt_VIN.Text = dr["VIN"].ToString();
                txt_Brand.Text = dr["Brand"].ToString();
                txt_VehicleName.Text = dr["VehicleName"].ToString();
                txt_EngineNo.Text = dr["EngineNo"].ToString();
                txt_RegNo.Text = dr["RegNo"].ToString();
                txt_ColorCode.Text = dr["ColorCode"].ToString();
                txt_Model.Text = dr["Model"].ToString();

                loadDetail();

            }
        }

        private void loadDataByServiceID()
        {
            Services sv = new Services();
            string sql = "select CustomerCode, VehicleCode,CustomerName, OtherName, Address, Tel, ";
            sql += " Tel, Mobile, TaxCode, ContactPerson, ContactPhone, ";
            sql += " VIN, Brand, VehicleName, EngineNo, RegNo, Model, ColorCode ";
            sql += " from U_GeneralService ";
            sql += "where GeneralID = " + Session["GeneralID"].ToString();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            
            if (ds.Tables[0].Rows.Count > 0)
            {
                generateNewAppID();
                loadDefaultData();
                DataRow dr = ds.Tables[0].Rows[0];
                hf_CustomerCode.Value = dr["CustomerCode"].ToString();
                hf_VehicleID.Value = dr["VehicleCode"].ToString();
                chk_CustomerCall.Checked = false;


                txt_CustomerName.Text = dr["CustomerName"].ToString();
                txt_OtherName.Text = dr["OtherName"].ToString();
                txt_Address.Text = dr["Address"].ToString();
                txt_Tel.Text = dr["Tel"].ToString();
                txt_Mobile.Text = dr["Mobile"].ToString();
                txt_TaxCode.Text = dr["TaxCode"].ToString();
                txt_ContactPerson.Text = dr["ContactPerson"].ToString();
                txt_PhoneContact.Text = dr["ContactPhone"].ToString();

                txt_VIN.Text = dr["VIN"].ToString();
                txt_Brand.Text = dr["Brand"].ToString();
                txt_VehicleName.Text = dr["VehicleName"].ToString();
                txt_EngineNo.Text = dr["EngineNo"].ToString();
                txt_RegNo.Text = dr["RegNo"].ToString();
                txt_ColorCode.Text = dr["ColorCode"].ToString();
                txt_Model.Text = dr["Model"].ToString();

            }
        }
        private void loadCustomer() {
            MasterData masterDataWS = new MasterData();
            DataSet ds = masterDataWS.GetCustomerByCode("VSM", hf_CustomerCode.Value);
            if (ds.Tables[0].Rows.Count > 0)
            {
                txt_CustomerName.Text = ds.Tables[0].Rows[0]["CardName"].ToString();
                txt_OtherName.Text = ds.Tables[0].Rows[0]["CardFName"].ToString();
                txt_Address.Text = ds.Tables[0].Rows[0]["Address"].ToString();
                txt_Tel.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
                txt_TaxCode.Text = ds.Tables[0].Rows[0]["LicTradNum"].ToString();
                txt_ContactPerson.Text = ds.Tables[0].Rows[0]["U_ContactPerson"].ToString();
                txt_PhoneContact.Text = ds.Tables[0].Rows[0]["U_ContactPhone"].ToString();
            }
        }

        private void loadVehicle(string VIN) {
            //Services sv = new Services();
            //if (jobkind == "004")
            //{
            //    string sql = "select  rn.DistNumber as VIN, rn.Notes as EngineNo, ms.Name as Model, ";
            //    sql += " cg.RegistrationNumber as RegNo, ";
            //    sql += " it.ItemName as VehicleName, rn.U_KeyNo as KeyNo, ms.Code as ModelCode, ";
            //    sql += " it.U_Color as ColorCode, rn.LotNumber as LotNo, it.UserText as Remarks, '' as Brand";

            //    sql += " from  OSRN rn ";
            //    sql += " join OITM it on it.ItemCode = rn.ItemCode ";
            //    sql += " join [@ModelSales] ms on ms.Code = it.U_ModelSales ";
            //    sql += " left join U_CustomerRegis cg on cg.VIN = rn.DistNumber ";
            //    sql += " where rn.DistNumber = '" + VIN + "' ";
            //    DataSet ds = sv.ExecuteQuery("VSM", sql);
            //    if (ds.Tables[0].Rows.Count > 0)
            //    {
            //        txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
            //        txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
            //        txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();
            //        txt_ColorCode.Text = ds.Tables[0].Rows[0]["ColorCode"].ToString();
            //        txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
            //    }
            //}
            //else
            //{
            //    DataSet ds = sv.ExecuteQuery("DEALER", "select * from U_ServiceVehicle where VehicleID = " + hf_VehicleID.Value);
            //    if (ds.Tables[0].Rows.Count > 0)
            //    {
            //        txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
            //        txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
            //        txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();
            //        txt_ColorCode.Text = ds.Tables[0].Rows[0]["ColorCode"].ToString();
            //        txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
            //    }
            //}
        }

        private void loadDetail() {
            Services sv = new Services();
            string sql = " SELECT ROW_NUMBER() OVER (ORDER BY DetailCode) AS No, * from U_ReservationDetail ";
            sql += " where Status <> 1 AND ResID = " + Session["ResID"].ToString();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            Session["dtDetail"] = ds.Tables[0];
            grvPO.DataSource = ds.Tables[0];
            grvPO.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            if (tblData.Rows.Count > 0)
            {
                DataRow dr = tblData.Rows[0];
                //txtDealerCode.Text = dr["CardCode"].ToString();
                //txtDealerName.Text = dr["CardName"].ToString();
                //txtAddress.Text = dr["Address"].ToString();
                //txtTaxCode.Text = dr["LicTradNum"].ToString();
                //txtTel1.Text = dr["Phone1"].ToString();
                //txtTel2.Text = dr["Phone2"].ToString();
                //txtMobilePhone.Text = dr["Cellular"].ToString();
                //txtEmail.Text = dr["E_mail"].ToString();
                //txtFax.Text = dr["Fax"].ToString();
            }
            
        }

        protected void btn_New_Click(object sender, EventArgs e)
        {
          
            //txtPONo.Text = "PO-" + "003/0414";
            //txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
      
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            //if (txtDealerCode.Text == "")
            //{
            //    Session["errorMessage"] = "Missing Dealer Code";
            //    Session["requestXML"] = "";
            //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Dealer Code','');", true);
            //}
            /*
            String requestXML = _collectData();
            Transaction ts = new Transaction();

            DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.BUSINESS_PARTNER).ToString(), txtDealerCode.Text, !string.IsNullOrEmpty(DealerCode.Value), Utils.AppConstants.VSM
            );

            if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
            {
                Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                Session["requestXML"] = requestXML;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
            }
            else
            {
                Session["successMessage"] = "Operation complete sucessful!";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
       
             */
        }
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               // Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
               // this.btnShowPopup.Enabled = true;
            }
            catch
            {
                //this.btnShowPopup.Enabled = false;
            }
            //UpdatePrice();
        }
        
 
        /// <summary>
        /// 
        /// </summary>
        private void ResetPage()
        {

            /*this.txtVendorCode.Text = "";
            this.txtVendorName.Text = "";
            this.Session["ChosenItem"] = null;
            this.Session["ChosenVendorCode"] = null;
            this.Session["ChosenVendorName"] = null;
            Session["SODATA"] = null;
            LoadOrderWareHouse();
            LoadData();
            this.btnUpdate.Enabled = false;*/
        }

       
      
        protected void TextBox_Change(object sender, EventArgs e)
        {
            // string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            TextBox tb = (TextBox)sender;
            string ItemCode = "'" + tb.Text + "'";
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lb_No");
            int rowNo = Int32.Parse( lblNo.Text) -1;
            int index = 0;
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            foreach (DataRow dr in dtTmp.Rows)
            {
                if (rowNo == index) {

                    MasterData mt = new MasterData();
                    DataSet dsItem = mt.GetItemsByItemCodeList("VSM", Utils.AppConstants.ID_Dealer, ItemCode);
                    
                    if (dsItem.Tables[0].Rows.Count == 1) {
                        dr["ItemCode"] = dsItem.Tables[0].Rows[0]["ItemCode"];
                        dr["ItemName"] = dsItem.Tables[0].Rows[0]["ItemName"];
                        dr["FrgnName"] = dsItem.Tables[0].Rows[0]["FrgnName"];
                        dr["Quantity"] = 1;
                        dr["Price"] = 0;//dsItem.Tables[0].Rows[0]["Price"];
                        dr["VAT"] = 10;//dsItem.Tables[0].Rows[0]["VAT"];
                        dr["DiscPrcnt"] = 10;//dsItem.Tables[0].Rows[0]["Discount"];
                        dr["Stock"] = 0; //dsItem.Tables[0].Rows[0]["Stock"];
                        Session["dtDetail"] = dtTmp;
                        grvPO.DataSource = dtTmp;

                        grvPO.DataBind();

                        this.lblError.Visible = false;
                        break;
                    }
                    else if (dsItem.Tables[0].Rows.Count > 1)
                    {
                        string msg = "Available parts: ";
                        foreach (DataRow drItem in dsItem.Tables[0].Rows)
                        {
                            msg += "";
                        }
                        this.lblError.Text = msg;
                        this.lblError.Visible = true;
                        break;
                    }
                    else { //=0
                        this.lblError.Text = "There is no part with code [" + tb.Text + "] available ";
                        this.lblError.Visible = true;
                    }
                    
                }
                index++;
            }

            
           

            //ListViewItem lvi = e.Item;

            //Label lblNo = (Label)lvi.FindControl("lblNo");
            //foreach (DataRow row in dtContents.Rows)
            //{
            //    if (row["No"].ToString().Equals(lblNo.Text)) // update currentrow into data table
            //    {
            //        Label lx = (Label)lvi.FindControl("ItemName");
            //        lx.Text = "Ha ha ha ha";

            //        //row["ItemCode"] = ((Label)lvi.FindControl("lblCode")).Text;
            //        //row["Dscription"] = ((Label)lvi.FindControl("lblDescription")).Text;
            //        //row["Quantity"] = ((TextBox)lvi.FindControl("txtQuantity")).Text;
            //        break;
            //    }
            //}
        }

        protected void btn_AddMultiItems_Click(object sender, EventArgs e)
        {
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            DataRow dr = dtTmp.NewRow();
            dr["No"] = dtTmp.Rows.Count + 1;
            dr["DetailCode"] = -1;
            dr["ItemCode"] = "";
            dr["ItemName"] = "";
            dr["FrgnName"] = "";
            dr["Quantity"] = 1;
            dr["Price"] = 0;
            dr["VAT"] = 10;
            dr["DiscPrcnt"] = 10;
            dr["Stock"] = 0;

            dtTmp.Rows.Add(dr);
            this.grvPO.DataSource = dtTmp;
            this.grvPO.DataBind();
            Session["dtDetail"] = dtTmp;
        }

        //RUKOWEN ADDED
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    GridViewRow myRow = e.Row;
            //    Label lblNo = myRow.FindControl("lblNo") as Label;
            //    lblNo.Text = (myRow.RowIndex + 1).ToString();
            //    //if (this.hdnStatus.Value == "C")
            //    //{
            //    //    TextBox txtQuantity = myRow.FindControl("txtOrderQuantity") as TextBox;
            //    //    txtQuantity.Enabled = false;
            //    //}
            //}
        }

        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvPO.PageIndex = e.NewPageIndex;
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            BindData(tblPOR1);
        }

        private void CalcTotal(DataTable tb)
        {
            try
            {
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["VatPrcnt"] != null && row["VatPrcnt"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["VatPrcnt"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }
                documentTotal += subTotal + gstTotal;
                //this.lblDocumentTotal.Text = string.Format("{0:C}", Math.Round(documentTotal, 2));
                //this.lblTaxAmount.Text = string.Format("{0:C}", Math.Round(gstTotal, 2));
                //this.lblSubTotal.Text = string.Format("{0:C}", Math.Round(subTotal, 2));
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            /*
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                int index = 0;
                TextBox ddl1 = e.Row.FindControl("txtOrderQuantity") as TextBox;
                ddl1.Attributes.Add("onfocus", "JavaScript:document.getElementById('" + ddl1.ClientID + "').select();");
                if (ViewState["rowindex"] != null && Session["POTable"] != null)
                {
                    index = Convert.ToInt32(ViewState["rowindex"].ToString());
                    int rowCount = ((DataTable)Session["POTable"]).Rows.Count;
                    if ((index + 1) <= this.grvPO.Rows.Count)
                    {
                        if (e.Row.RowIndex == index + 1)
                        {
                            ddl1.Focus();
                            //ScriptManager.GetCurrent(this).SetFocus(ddl1.ClientID);
                        }
                    }
                }
            }
             * */
        }

        private void saveGrid()
        {
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            dtTmp.Rows.Clear();

            foreach (GridViewRow row in grvPO.Rows)
            {
                DataRow newRow = dtTmp.NewRow();
                newRow["No"] = ((Label)row.FindControl("lb_No")).Text;
                newRow["DetailCode"] = ((Label)row.FindControl("lb_DetailCode")).Text;
                newRow["ItemCode"] = ((TextBox)row.FindControl("txt_ItemCode")).Text;
                newRow["ItemName"] = ((Label)row.FindControl("lb_ItemName")).Text;

                newRow["FrgnName"] = ((Label)row.FindControl("lb_FrgnName")).Text;
                newRow["Quantity"] = ((TextBox)row.FindControl("txt_Qty")).Text;
                newRow["Price"] = ((Label)row.FindControl("lb_Price")).Text;
                newRow["VAT"] = ((Label)row.FindControl("lb_VAT")).Text;
                newRow["DiscPrcnt"] = ((TextBox)row.FindControl("txt_DiscPrcnt")).Text;
                newRow["Stock"] = ((Label)row.FindControl("lb_Stock")).Text;
                dtTmp.Rows.Add(newRow);
            }

            Session["dtDetail"] = dtTmp;
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                saveGrid();
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lb_No");
                int rowNo = Int32.Parse(lblNo.Text);
                DataTable dtTmp = (DataTable)Session["dtDetail"];
                Services sv = new Services();
                foreach (DataRow dr in dtTmp.Rows)
                {
                    if (rowNo == Int32.Parse(dr["No"].ToString()))
                    {
                        string DetID = dr["DetailCode"].ToString();
                        if (DetID != "-1")
                        {
                            DataSet dsDel = new DataSet();
                            DataTable dtDel = new DataTable();
                            dtDel.Columns.Add("DetailCode");
                            DataRow drDel = dtDel.NewRow();
                            drDel["DetailCode"] = DetID;

                            dtDel.Rows.Add(drDel);
                            dsDel.Tables.Add(dtDel);

                            sv.DeleteReservationDetail("DEALER", dsDel);
                        }
                        dr.Delete();
                        break;
                    }
                }
                //reset number
                int index = 0;
                foreach (DataRow dr in dtTmp.Rows)
                    dr["No"] = ++index;

                Session["dtDetail"] = dtTmp;
                grvPO.DataSource = dtTmp;
                grvPO.DataBind();

            }
            catch (Exception ex)
            {
                //this.lblError.Text = ex.Message;
                //this.lblError.Visible = true;
            }
        }

        public void updateRowTotalPrice(DataRow row, string currColName)
        {
            double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, total = 0;
            quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
            unitPrice = GF.Object2Double(GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
            discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");
            priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");

            total = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

            if (string.IsNullOrEmpty(currColName))
                row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt"))
                row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt") || currColName.Equals("Quantity"))
                row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");

            row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
            row["LineTotal"] = GF.FormatNumeric(total.ToString(), "SumDec");

        }

        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                
                //GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                //ViewState["rowindex"] = row.RowIndex;
                //TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                //if (txtQuantity.Text.Trim().Length == 0)
                //{
                //    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                //    txtQuantity.Focus();
                //    return;
                //}
                //Label lblItemCode = (Label)row.FindControl("lblItemCode");

                //DataTable tb = (DataTable)Session["POR1Table"];
                //if (tb != null)
                //{
                //    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                //    if (rupdate.Length > 0)
                //    {
                //        rupdate[0]["Quantity"] = txtQuantity.Text;
                //        updateRowTotalPrice(rupdate[0], "Quantity");
                //    }
                //}

                //this.grvPO.EditIndex = -1;

                //BindData(tb);
                //CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
           
        }

        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtUnitPrice.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            this.grvPO.EditIndex = e.NewEditIndex;
            BindData((DataTable)Session["POR1Table"]);
        }

        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            this.grvPO.EditIndex = -1;
            BindData((DataTable)Session["POR1Table"]);
        }

        private void GetPrice(DataRow r)
        {
            try
            {
                /*
                DataSet ds = GetDataItem(DateTime.Parse(this.txtPODate.Text.Trim()), r["ItemCode"].ToString(), this.txtVendorCode.Text, double.Parse(r["Quantity"].ToString()));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                    {
                        r["Price"] = (decimal.Parse(ds.Tables[0].Rows[0]["NumInBuy"].ToString()) * decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    else
                    {
                        r["Price"] = decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    r["LineTotal"] = (double.Parse(r["Price"].ToString()) * double.Parse(r["Quantity"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                }
                 * */
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvPO.EditIndex = -1;
                    BindData((DataTable)Session["POR1Table"]);
                    CalcTotal(((DataTable)Session["POR1Table"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                    }

                    this.grvPO.EditIndex = -1;

                    BindData(tb);
                    CalcTotal(tb);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void txtDiscPrcnt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
                if (txtDiscPrcnt.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtDiscPrcnt.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
                        updateRowTotalPrice(rupdate[0], "DiscPrcnt");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btn_ImportPackage_Click(object sender, EventArgs e)
        {
            //string selectedPackage = ddl_Package.SelectedValue.ToString();
            //if (selectedPackage != "-1")
            //{
            //    Services sv = new Services();
            //    DataSet ds =  sv.ExecuteQuery("VSM", "select PacDetID, ItemCode, Quantity from  U_PackageDetail where PackageID = " + selectedPackage);
            //    if (ds.Tables[0].Rows.Count > 0) {
            //        DataTable dtTmp = (DataTable)Session["dtDetail"];
            //        foreach (DataRow dr in ds.Tables[0].Rows) {
            //            string ItemCode = dr["ItemCode"].ToString();
            //            double qty = Double.Parse( dr["Quantity"].ToString());
            //            dtTmp.Rows.Add(GetLineInfo(ItemCode, qty));
            //        }
            //        grvPO.DataSource = dtTmp;
            //        grvPO.DataBind();
            //        Session["dtDetail"] = dtTmp;
            //    }
            //}

        }


        private DataRow GetLineInfo(string ItemCode, double qty)
        {
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            DataRow dr = dtTmp.NewRow();
            GetDefault defaultWS = new GetDefault();
            MasterData mt = new MasterData();
            DataSet dsItem = mt.GetItemsByItemCodeList("VSM", Session[Utils.AppConstants.ID_Dealer].ToString(), "'"+ItemCode+"'");

            DataSet defaultInfo = null; //defaultWS.GetDefaultLineInfo("VSM", Session[Utils.AppConstants.ID_Dealer].ToString(),
                        //"VS", ItemCode, qty, DateTime.Now);
           
            dr["DetailCode"] = -1;
            dr["No"] = dtTmp.Rows.Count + 1;
            dr["ItemCode"] = ItemCode;
            dr["ItemName"] = dsItem.Tables[0].Rows[0]["ItemName"];
            dr["FrgnName"] = dsItem.Tables[0].Rows[0]["FrgnName"];
            dr["Quantity"] = qty;
            dr["Price"] = defaultInfo.Tables[0].Rows[0]["UnitPrice"];
            dr["VAT"] = 10;
            dr["DiscPrcnt"] = defaultInfo.Tables[0].Rows[0]["Discount"];
            dr["Stock"] = 0; //dsItem.Tables[0].Rows[0]["Stock"];

            return dr;
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            saveGrid();
            DataTable dt = new DataTable();
            dt.Columns.Add("ResID");
            dt.Columns.Add("SeqNo");
            dt.Columns.Add("ServiceStaff");
            dt.Columns.Add("ResDate");
            dt.Columns.Add("ResTime");
            dt.Columns.Add("DeliveryDate");

            dt.Columns.Add("DeliveryTime");
            dt.Columns.Add("ConfirmDate");
            dt.Columns.Add("ConfirmTime");
            dt.Columns.Add("CustomerCall");
            dt.Columns.Add("EstimateCost");

            dt.Columns.Add("PODate");
            dt.Columns.Add("POTime");
            dt.Columns.Add("PADate");
            dt.Columns.Add("PATime");
            dt.Columns.Add("CustomerRequest");

            dt.Columns.Add("VehicleID");
            dt.Columns.Add("VIN");
            dt.Columns.Add("Brand");
            dt.Columns.Add("VehicleName");
            dt.Columns.Add("EngineNo");

            dt.Columns.Add("RegNo");
            dt.Columns.Add("Model");
            dt.Columns.Add("ColorCode");
            dt.Columns.Add("Odometer");
            dt.Columns.Add("CustomerID");

            dt.Columns.Add("CustomerName");
            dt.Columns.Add("OtherName");
            dt.Columns.Add("Address");
            dt.Columns.Add("Tel");
            dt.Columns.Add("Mobile");

            dt.Columns.Add("TaxCode");
            dt.Columns.Add("ContactPerson");
            dt.Columns.Add("ContactPhone");
            dt.Columns.Add("DealerCode");

            DataRow dr = dt.NewRow();
            dr["SeqNo"] = txt_SeqNo.Text;
            dr["ServiceStaff"] = txt_Receptionist.Text;

            if (txt_ResDate.Text.Trim() == "")
                dr["ResDate"] = DBNull.Value;
            else
                dr["ResDate"] = Utils.AppConstants.ConvertToDate(txt_ResDate.Text.Trim());

            dr["ResTime"] = txt_ResTime.Text;

            if (txt_DelDate.Text.Trim() == "")
                dr["DeliveryDate"] = DBNull.Value;
            else
                dr["DeliveryDate"] = Utils.AppConstants.ConvertToDate(txt_DelDate.Text.Trim());

            dr["DeliveryTime"] = txt_DelTime.Text;

             if (txt_ConfDate.Text.Trim() == "")
                dr["ConfirmDate"] = DBNull.Value;
            else
                dr["ConfirmDate"] = Utils.AppConstants.ConvertToDate(txt_ConfDate.Text.Trim());
            
            dr["ConfirmTime"] = txt_ConfTime.Text;
            dr["CustomerCall"] = chk_CustomerCall.Checked==true?1:0;
            dr["EstimateCost"] = txt_EstimateCost.Text;

            if (txt_PartOrderDate.Text.Trim() == "")
                dr["PODate"] = DBNull.Value;
            else
                dr["PODate"] = Utils.AppConstants.ConvertToDate(txt_PartOrderDate.Text.Trim());
            
            dr["POTime"] = txt_PartOrderTime.Text;

            if (txt_PartArrivalDate.Text.Trim() == "")
                dr["PADate"] = DBNull.Value;
            else
                dr["PADate"] = Utils.AppConstants.ConvertToDate(txt_PartArrivalDate.Text.Trim());

            dr["PATime"] = txt_PartArrivalTime.Text;
            dr["CustomerRequest"] = txt_CustomerRequest.Text;

            dr["VehicleID"] = hf_VehicleID.Value;
            dr["VIN"] = txt_VIN.Text;
            dr["Brand"] = txt_Brand.Text;
            dr["VehicleName"] = txt_VehicleName.Text;
            dr["EngineNo"] = txt_EngineNo.Text;

            dr["RegNo"] = txt_RegNo.Text;
            dr["Model"] = txt_Model.Text;
            dr["ColorCode"] = txt_ColorCode.Text;
            dr["Odometer"] = txt_Odometer.Text;
            dr["CustomerID"] = hf_CustomerCode.Value;

            dr["CustomerName"] = txt_CustomerName.Text;
            dr["OtherName"] = txt_OtherName.Text;
            dr["Address"] = txt_Address.Text;
            dr["Tel"] = txt_Tel.Text;
            dr["Mobile"] = txt_Mobile.Text;

            dr["TaxCode"] = txt_TaxCode.Text;
            dr["ContactPerson"] = txt_ContactPerson.Text;
            dr["ContactPhone"] = txt_PhoneContact.Text;
            dr["DealerCode"] =  Session[Utils.AppConstants.ID_Dealer].ToString();

            dr["ResID"] = Session["ResID"];

            Services svc = new Services();
            dt.Rows.Add(dr);
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            if (Session["ResID"].ToString() == "-1") //add new
            {
               
                int result = svc.InsertReservation("DEALER", ds);
                
                if (result != -1)
                {
                    Session["ResID"] = result;
                    hf_ResID.Value = result.ToString();
                    InsertUpdateDetail();
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Add New] Operation complete sucessful!');", true);
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Add New] Operation failed!');", true);                  
                }
            }
            else { //update
                int count = svc.UpdateReservation("DEALER", ds);
                if (count != -1)
                {
                    InsertUpdateDetail();
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Update] Operation complete sucessful!');", true);                
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('[Update] Operation failed!');", true);
                }
            }
            
        }

        private void InsertUpdateDetail() {
            DataSet dsDetail = new DataSet();
            DataTable dtDetail = new DataTable();
            dtDetail.Columns.Add("DetailCode");
            dtDetail.Columns.Add("ResID");
            dtDetail.Columns.Add("ItemCode");
            dtDetail.Columns.Add("ItemName");
            dtDetail.Columns.Add("FrgnName");
            dtDetail.Columns.Add("Quantity");
            dtDetail.Columns.Add("Price");
            dtDetail.Columns.Add("VAT");
            dtDetail.Columns.Add("DiscPrcnt");
            dtDetail.Columns.Add("Stock");
            Services svc = new Services();
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            foreach (DataRow drDetail in dtTmp.Rows)
            {
                dsDetail.Tables.Clear();
                DataRow toAdd = dtDetail.NewRow();

                toAdd["DetailCode"] = drDetail["DetailCode"];
                toAdd["ResID"] = Session["ResID"];
                toAdd["ItemCode"] = drDetail["ItemCode"];
                toAdd["ItemName"] = drDetail["ItemName"];
                toAdd["FrgnName"] = drDetail["FrgnName"];
                toAdd["Quantity"] = drDetail["Quantity"];
                toAdd["Price"] = drDetail["Price"];
                toAdd["VAT"] = drDetail["VAT"];
                toAdd["DiscPrcnt"] = drDetail["DiscPrcnt"];
                toAdd["Stock"] = drDetail["Stock"];
                dtDetail.Rows.Clear();
                dtDetail.Rows.Add(toAdd);
                dsDetail.Tables.Add(dtDetail);
                if (drDetail["DetailCode"].ToString() == "-1")
                    svc.InsertReservationDetail("DEALER", dsDetail);
                else
                    svc.UpdateReservationDetail("DEALER", dsDetail);

            }
        }
        protected void btn_ImportExcel_Click(object sender, EventArgs e)
        {
            /*
            if (fu_ImportExcel.HasFile)
            {
                string FileName = Path.GetFileName(fu_ImportExcel.PostedFile.FileName);
                string Extension = Path.GetExtension(fu_ImportExcel.PostedFile.FileName);
                string FolderPath = "ExcelTmpFile";

                string FilePath = Server.MapPath(Path.Combine(FolderPath, FileName));
                fu_ImportExcel.SaveAs(FilePath);


                HSSFWorkbook hssfwb;
                using (FileStream file = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                {
                    hssfwb = new HSSFWorkbook(file);

                }

                Sheet sheet = hssfwb.GetSheet("Sheet1");
                for (int row = 1; row <= sheet.LastRowNum; row++)
                {
                    if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
                    {
                        string ItemCode = sheet.GetRow(row).GetCell(2).StringCellValue;
                        double qty = sheet.GetRow(row).GetCell(4).NumericCellValue;

                        if (ItemCode.Trim() != "")
                        {

                            dtContents.Rows.Add(GetLineInfo(ItemCode, qty));
                        }
                    }
                }
                grvPO.DataSource = dtContents;
                grvPO.DataBind();
            }
             * */
        }
    }

}